﻿using PMSystem.DataAccess;
using PMSystem.DataAccess.DataRepository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PMSystem.ApplicationLogics
{
    public class UserService
    {
      
        public User GetUserByUserId(int id)
        {
            try
            {
                 using (var repo = new UserRepository())
                    {
                        var existinguser = repo.GetById(id);
                        if (existinguser != null)
                        {
                            return existinguser;
                        }
                    }
            }
            catch (Exception ex)
            {
                var errr = ex.Message;
            }
            return null;
        }

        public int CreateOrUpdateUser(User user)
        {
            try
            {
                if (user != null)
                    using (var repo = new UserRepository())
                    {
                        var encrypt = PasswordManager.Encrypt(user.Password);
                        user.Password = encrypt;

                        repo.InsertOrUpdate(user);
                        repo.Save();

                        return user.UserId;
                    }
            }
            catch (Exception ex)
            {
                var errr = ex.Message;
            }
            return 0;
        }

        public List<User> GetUsersBySearch(string keyword)
        {
            int[] adminuserid = new int[] { 1, 2 };
            List<User> results = new List<User>();
            using (var repo = new UserRepository())
            {
                results = repo.GetAll.Where(x => x.IsDeleted == false && !(adminuserid.Contains(x.UserId))).ToList();
            }
            if(!string.IsNullOrWhiteSpace(keyword))
            {
                results = results.Where(x =>
                    (x.FirstName !=null && x.FirstName.ToLower().Contains(keyword.ToLower()) )
                    ||
                    (x.LastName != null && x.LastName.ToLower().Contains(keyword.ToLower()))
                    ).ToList();

              
            }

            return results;
        }

        public bool DeleteUser(int id)
        {

            try
            {
                using (var repo = new UserRepository())
                {
                    var existinguser = repo.GetById(id);
                    if (existinguser != null)
                    {
                        existinguser.IsDeleted = true;
                        repo.InsertOrUpdate(existinguser);
                        repo.Save();
                        return true;
                    }
                }
            }
            catch (Exception ex)
            {
                var errr = ex.Message;
            }
            return false;
        }

        public void AddUserToRoles(int userid, List<string> roleList)
        {
            try
            {
                using (var repo = new UserRolesRepository())
                {
                    foreach(var role in roleList)
                    {

                        var roleid = GetRoleIdByName(role);
                        if(roleid>0)
                        {
                            var newuserRole = new UserRole()
                            {
                                UserId = userid,
                                RoleId = roleid
                            };
                            repo.InsertOrUpdate(newuserRole);
                            repo.Save();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                var errr = ex.Message;
            }
        }

        private int GetRoleIdByName(string name)
        {
            int id = 0;
            try{
            using (var repo = new RolesRepository())
            {
                var role = repo.GetAllByCondition(x => x.RoleName.ToLower() == name.ToLower()).FirstOrDefault();
                if (role != null)
                    id= role.RoleId;
            }
            }
            catch (Exception ex)
            {
                var errr = ex.Message;
            }

            return id;
        }

        private void DeleteExsistingRoles(int userid)
        {
            try
            {
                using (var repo = new UserRolesRepository())
                {
                    var roleList = repo.GetAllByCondition(x => x.UserId == userid);
                    if(roleList!=null && roleList.Any())
                    {
                        repo.DeleteList(roleList);
                    }
                }
            }
            catch (Exception ex)
            {
                var errr = ex.Message;
            }
        }

        public User ValidateLogin(string username, string password)
        {
            User _user= null;
            try
            {
                using (var repo = new UserRepository())
                {
                    var decrptPwd = PasswordManager.Encrypt(password);
                    _user = repo.GetAllByCondition(x => x.UserName == username
                        && x.Password == decrptPwd
                        && x.IsDeleted == false).FirstOrDefault();
                   
                }
            }
            catch (Exception ex)
            {
                var errr = ex.Message;
            }

            return _user;
        }

        public bool IsUserNameAvailable(string username)
        {
            bool isavailable = false;
            
            try
            {
                using (var repo = new UserRepository())
                {
                    isavailable = repo.GetAllByCondition(x => x.UserName == username && x.IsDeleted == false).Any();

                }
            }
            catch (Exception ex)
            {
                var errr = ex.Message;
            }

            return isavailable;
        }

        public List<UserRole> GetUserRoles(int userid)
        {
            try
            {
                using (var repo = new UserRolesRepository())
                {
                   return repo.GetAllByCondition(x => x.UserId == userid);
                }
            }
            catch (Exception ex)
            {
                var errr = ex.Message;
            }
            return null;
        }
    }
}
